package com.help.knowhelps.commond;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class CharacterAESCrypt {
	
	private static byte[] rawKey;
	
	private static Cipher encryptCipher;
	
	private static Cipher decryptCipher;
	
	private static SecretKeySpec skeySpec;
	
	private static final int JELLY_BEAN_4_2 = 17;

	
	public static byte[] encrypt(String aesSeed,byte[]buf)
			throws Exception {
		
//		if(rawKey == null || rawKey.length == 0) {
			rawKey = getRawKey(aesSeed.getBytes());
//		}
		return encrypt(rawKey, buf);
	}
	
	public static byte[] decrypt(String aesSeed,byte[]buf)
			throws Exception {
		
//		if(rawKey == null || rawKey.length == 0) {
			rawKey = getRawKey(aesSeed.getBytes());
//		}
		return decrypt(rawKey, buf);
	}

	protected static byte[] getRawKey(byte[] seed) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom sr = null;
		if(android.os.Build.VERSION.SDK_INT >= JELLY_BEAN_4_2) {
			sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
		}
		else {
			sr = SecureRandom.getInstance("SHA1PRNG");
		}
		sr.setSeed(seed);
		kgen.init(128, sr); // 192 and 256 bits may not be available
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		return raw;
	}

	protected static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
		
//		if(skeySpec == null) {
			 skeySpec = new SecretKeySpec(raw, "AES");
//		}
//		if(encryptCipher == null) {
			encryptCipher = Cipher.getInstance("AES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
//		}
		byte[] encrypted = encryptCipher.doFinal(clear);
		return encrypted;
	}

	protected static byte[] decrypt(byte[] raw, byte[] encrypted)
			throws Exception {
//		if(skeySpec == null) {
			 skeySpec = new SecretKeySpec(raw, "AES");
//		}
//		if(decryptCipher == null) {
			decryptCipher = Cipher.getInstance("AES");
			decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec);
//		}
		byte[] decrypted = decryptCipher.doFinal(encrypted);
		return decrypted;
	}

}
